package com.common.android.utils.http;

import java.io.IOException;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.ssl.SSLSocketFactory;

/**
 * SSLSocket相关工具类
 * <br>Created 2014-8-26 上午11:21:03
 * @version  
 * @author   huangyx		
 * @see 	 
 * Copyright(c) 2009-2014, TQ Digital Entertainment, All Rights Reserved
 */
public class SSLSocketFactoryEx extends SSLSocketFactory {

	SSLContext sslContext = SSLContext.getInstance("TLS");

	/**
	 * Creates a new instance of SSLSocketFactoryUtils.
	 * <br>Created 2014-8-26 上午11:22:42
	 * @param truststore 
	 * @throws NoSuchAlgorithmException   
	 * @throws KeyManagementException   
	 * @throws KeyStoreException   
	 * @throws UnrecoverableKeyException   
	 */
	public SSLSocketFactoryEx(KeyStore truststore) throws NoSuchAlgorithmException, 
	        KeyManagementException, KeyStoreException, UnrecoverableKeyException {
		super(truststore);

		TrustManager tm = new X509TrustManager() {
			public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return null;
			}

			@Override
			public void checkClientTrusted(java.security.cert.X509Certificate[] chain, 
			        String authType) throws java.security.cert.CertificateException {
			}

			@Override
			public void checkServerTrusted(java.security.cert.X509Certificate[] chain, 
			        String authType) throws java.security.cert.CertificateException {
			}
		};
		sslContext.init(null, new TrustManager[] { tm }, null);
	}

	/**
	 * 创建SSLSocket
	 * <br>Created 2014-8-26 上午11:22:57
	 * @param socket Socket对象
	 * @param host 主机
	 * @param port 端口
	 * @param autoClose 是否自动关闭
	 * @return SSLSocket对象
	 * @throws IOException 
	 * @author       huangyx
	 */
	@Override
	public Socket createSocket(Socket socket, String host, int port, boolean autoClose) 
	        throws IOException {
		return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
	}

	/**
	 * 创建Socket
	 * <br>Created 2014-8-26 上午11:23:14
	 * @return Socket对象
	 * @throws IOException 
	 * @author       huangyx
	 */
	@Override
	public Socket createSocket() throws IOException {
		return sslContext.getSocketFactory().createSocket();
	}
}